package com.yunkaweilai.android.view;

import android.content.Context;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.yunkaweilai.android.R;

/**
 * Created by Administrator on 2017/6/23.
 */

public class MyToast {
    private static Toast mToast;

    private static Handler mHandler = new Handler();
    private static Runnable r = new Runnable() {
        public void run() {
            mToast.cancel();
            mToast=null;//toast隐藏后，将其置为null
        }
    };

    public static void showShortToast(Context context, String message) {
        //当API>=28的时候，对Toast这里进行修改，解决弹窗第二次快速点击的时候无法显示的问题
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
//            Toast.makeText(context, message, duration).show();
//        } else
        if (context != null){
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.view_toast, null);//自定义布局
            TextView text = (TextView) view.findViewById(R.id.id_tv_toast);//显示的提示文字
            text.setText(message);
            mHandler.removeCallbacks(r);
            if (mToast == null){//只有mToast==null时才重新创建，否则只需更改提示文字
                mToast = new Toast(context);
                mToast.setDuration(Toast.LENGTH_SHORT);
                mToast.setGravity(Gravity.BOTTOM, 0, 150);
                mToast.setView(view);
            }
            mHandler.postDelayed(r, 1000);//延迟1秒隐藏toast
            mToast.show();
        }

    }
    public static void showShortToast(Context context, int res) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.view_toast, null);//自定义布局
        TextView text = (TextView) view.findViewById(R.id.id_tv_toast);//显示的提示文字
        text.setText(res);
        mHandler.removeCallbacks(r);
        if (mToast == null){//只有mToast==null时才重新创建，否则只需更改提示文字
            mToast = new Toast(context);
            mToast.setDuration(Toast.LENGTH_SHORT);
            mToast.setGravity(Gravity.BOTTOM, 0, 150);
            mToast.setView(view);
        }
        mHandler.postDelayed(r, 1000);//延迟1秒隐藏toast
        mToast.show();
    }


}
